package httpclient;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientApp {
    public static void main(String[] args) throws Exception{
        asyncSendGet();
    }
    public static void syncSendGet() throws Exception{
        HttpClient httpClient= HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://httpbin.org/get?name=john"))
                .GET().build();
        String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
        System.out.println(body);
    }

    public static void syncSendPost() throws Exception{
        HttpClient httpClient= HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://httpbin.org/post"))
                .header("Content-Type","application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString("name=john")).build();
        String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
        System.out.println(body);
    }

    public static void asyncSendGet() throws Exception{
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://httpbin.org/get?name=john"))
                .GET().build();
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(resp->resp.body())
                .thenAccept(System.out::println);
        System.out.println("end.....");
        System.in.read();
    }
}
